<?php
	require('config.php');
	file_put_contents("tsxx_alipay.txt", "\r\n--------------------------\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n收到支付宝回调通知:".date('Y-m-d H:i:s')."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n返回信息：".json_encode($_POST)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n商户单号：".$_POST['out_trade_no']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n商品名称：".$_POST['subject']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n支付宝交易号：".$_POST['trade_no']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n买家账号：".$_POST['buyer_email']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n交易金额：".$_POST['total_fee']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n支付宝交易号：".$_POST['trade_no']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_alipay.txt", "\r\n--------------------------\r\n", FILE_APPEND);

	$time=date('Y-m-d H:i:s');
	$time2=time();
	if(isset($_POST['trade_status']) && $_POST['trade_status']=='TRADE_SUCCESS')
	{
		//收到支付成功信息
		$body=explode(',',$_POST['body']);//获取orderId列表
		$body_type=$body[0];
		if($body_type=='orderId')
		{
			$user_id=0;
			$lin_max_pan=0;
			$json_0=$body[1];
			$json[0]=$json_0;
			$sql="select userId,isPay,orderStatus FROM ".$oto."_orders where orderId='{$json_0}'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$lin_user_order[]=$row;//将取得的所有数据赋值给person_info数组
			}
			if($lin_user_order[0]['isPay']==1 && $lin_user_order[0]['orderStatus']!=-2) exit();
			if(isset($lin_user_order)) $user_id=$lin_user_order[0]['userId'];
			$sql="select * from `".$oto."_users` where `userId`='".$user_id."' LIMIT 1";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$user_info[]=$row;//将取得的所有数据赋值给person_info数组
			}
			$pay_money=0;
			for($i=0;$i<count($json);$i++)
			{
				$order_id=$json[$i];
				$sql="select * from `".$oto."_orders` where `orderId`='".$order_id."' LIMIT 1";
				$result=$db->query($sql);
				while($row=$result->fetch_assoc()){
					$order[$i]=$row;//将取得的所有数据赋值给person_info数组
				}
				$pay_money+=$order[$i]['needPay'];
				if($order[$i]['isPay']==1 || $order[$i]['isPay']=='1')
				{
					$data[0]['pan']=-3;
					$data[0]['msg']=$order[$i]['orderNo']."已付过款";
					// echo json_encode($data);
					// exit();
				}
			}
			//$msg['total_fee']=$msg['total_fee']/100;
			// if($pay_money!=$msg['total_fee'])
			// {
			// 	$user_lin_money=$msg['total_fee'];
			// 	$tarde_no=$msg['trade_no'];
			// 	$user_money_lin2=$user_info[0]['userMoney']+$user_lin_money;
			// 	$sql="update ".$oto."_users set userMoney='{$user_money_lin2}' where userId='{$user_id}'";
			// 	$result=$db->query($sql);
			// 	$sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`balance`,`time`,`IncDec`,`type`,`remark`,`payWay`) VALUES ('$user_id','$tarde_no','$user_lin_money','$user_money_lin2','$time2','1','3','支付宝退款','1')";
	  //           $result=$db->query($sql);
			// 	echo "success";
			// 	exit();
			// }
				if($lin_max_pan==0)//通过验证了
				{
					//减少商品库存
					for($i=0;$i<count($json);$i++)
					{
						$order_id=$json[$i];
						$sql="select * from `".$oto."_order_goods` where `orderId`='".$order_id."'";
						$result=$db->query($sql);
						while($row=$result->fetch_assoc()){
							$lin_goods[$i][]=$row;//将取得的所有数据赋值给person_info数组
						}
						for($j=0;$j<count($lin_goods);$j++)
						{
							$goods_id=$lin_goods[$i][$j]['goodsId'];
							$goods_attr_id=$lin_goods[$i][$j]['goodsAttrId'];
							$goods_num=$lin_goods[$i][$j]['goodsNums'];
							$lin_pan=0;
							$sql="select * from `".$oto."_goods` where `goodsId`='".$goods_id."' LIMIT 1";
							$result=$db->query($sql);
							while($row=$result->fetch_assoc()){
								$lin_goods_info[$j]=$row;//将取得的所有数据赋值给person_info数组
							}
							$goodsStock=$lin_goods_info[$j]['goodsStock'];
							$hgoodsStock=$goodsStock-$goods_num;
							$hsaleCount=$lin_goods_info[$j]['saleCount']+$goods_num;
							$sql="update ".$oto."_goods set goodsStock='{$hgoodsStock}' where goodsId='{$goods_id}'";
							$result=$db->query($sql);
							if($goodsStock<$goods_num)
							{
								// $lin_pan=1;
								// $lin_max_pan=1;
							}
							else
							{
								if($goods_attr_id==null || $goods_attr_id=="")
								{

								}
								else
								{
									$goods_attr_id=explode(',',$goods_attr_id);
									for($k=0;$k<count($goods_attr_id);$k++)//减少属性库存
									{
										$attr_id=$goods_attr_id[$k];
										$sql="select * from `".$oto."_goods_attributes` where `id`='".$attr_id."' LIMIT 1";
										$result=$db->query($sql);
										while($row=$result->fetch_assoc()){
											$attr_info[$k]=$row;//将取得的所有数据赋值给person_info数组
										}
										$attrStock=$attr_info[$k]['attrStock'];
										$hattrStock=$attrStock-$goods_num;
										$sql="update ".$oto."_goods_attributes set attrStock='{$hattrStock}' where id='{$attr_id}'";
										$result=$db->query($sql);
										// if($attr_info[$k]['attrStock']<$goods_num)
										// {
										// 	$lin_pan=1;
										// 	$lin_max_pan=1;
										// }
									}
								}
							}
							// if($lin_pan==1)
							// {
							// 	$data[0]['pan']=-3;
							// 	$data[0]['msg'].=$lin_goods_info[$j]['goodsName'].'库存不足！\n\r';
							// }
						}
					}
					/****************判断库存等验证通过时修改订单状态以及减少用户余额****************/
					for($i=0;$i<count($json);$i++)
					{
						$order_id=$json[$i];
						$sql="update ".$oto."_orders set orderStatus='0',payType='1',paytime='{$time2}',isPay='1' where orderId='{$order_id}'";
						$result=$db->query($sql);
						//file_put_contents("tsxx.txt", "\r\n".$sql."执行：".$result."\r\n", FILE_APPEND);
						$createTime=date('Y-m-d H:i:s');
						$sql="INSERT INTO ".$oto."_log_orders (`orderId`,`logContent`,`logUserId`,`logType`,`logTime`) VALUES ('$order_id','下单成功','$user_id','0','$createTime')";
	            		$result=$db->query($sql);
						$sql="select * FROM ".$oto."_orders where orderId='{$order_id}'";
						$result=$db->query($sql);
						while($row=$result->fetch_assoc()){
							$score_order_lin[$i]=$row;//将取得的所有数据赋值给person_info数组
						}
						$order_no=$score_order_lin[$i]['orderNo'];
						$needPay_lin=$score_order_lin[$i]['needPay'];
						$user_score_lin=$user_info[0]['userScore']+$needPay_lin;
						$user_money_lin=$user_info[0]['userMoney'];
						// $sql="INSERT INTO ".$oto."_score_record (`userid`,`orderNo`,`score`,`totalscore`,`time`,`IncDec`,`type`) VALUES ('$user_id','$order_no','$needPay_lin','$user_score_lin','$time2','1','1')";
	     //        		$result=$db->query($sql);
	            		$sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`balance`,`time`,`IncDec`,`type`,`remark`,`payWay`) VALUES ('$user_id','$order_no','$needPay_lin','$user_money_lin','$time2','0','1','购买商品(支付宝支付)','1')";
	            		//file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
	            		$result=$db->query($sql);
					}
					$user_money=$user_info[0]['userMoney']-$pay_money;
					$user_score=$user_info[0]['userScore']+$pay_money;
					// $sql="update ".$oto."_users set userMoney='{$user_money}',userScore='{$user_score}' where userId='{$user_id}'";
					// $result=$db->query($sql);
					// $sql="update ".$oto."_users set userScore='{$user_score}' where userId='{$user_id}'";
					// $result=$db->query($sql);
					// if($result)
					// {
					// 	$data[0]['pan']=1;
					// }
					// else
					// {
					// 	for($i=0;$i<count($json);$i++)
					// 	{
					// 		$order_id=$json[$i];
					// 		$sql="update ".$oto."_orders set orderStatus='-2' where orderId='{$order_id}'";
					// 		$result=$db->query($sql);
					// 	}
					// 	$data[0]['pan']=-2;
					// 	$data[0]['msg']='支付异常';
					// }
					/********************************/

					/************增加优惠券使用记录并减少未使用优惠券**************/
					for($i=0;$i<count($json);$i++)
					{
						$order_id=$json[$i];
						$sql="select * from `".$oto."_orders` where `orderId`='".$order_id."'";
						$result=$db->query($sql);
						while($row=$result->fetch_assoc()){
							$order_youhui_info[$i]=$row;//将取得的所有数据赋值给person_info数组
						}
						$order_youhui_id=$order_youhui_info[$i]['couponId'];
						if($order_youhui_id!=0 && $order_youhui_id!='0')
						{
							$order_youhui_id=$order_youhui_info[0]['couponId'];
							$order_youhui_money=$order_youhui_info[0]['couponMoney'];
							$sql="select * from `".$oto."_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
							$result=$db->query($sql);
							while($row=$result->fetch_assoc()){
								$yhq_yz[]=$row;//将取得的所有数据赋值给person_info数组
							}
							if(isset($yhq_yz))
							{
								if($yhq_yz[0]['surplus']>1)
								{
									$surplus=$yhq_yz[0]['surplus']-1;
									$l_shopId=$yhq_yz[0]['shop_id'];
									$sql="update ".$oto."_youhui_user_link set surplus='{$surplus}' where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
									$result=$db->query($sql);
									$sql="INSERT INTO ".$oto."_youhui_use_record (`youhui_id`,`userId`,`shopId`,`useTime`,`orderId`,`money`) VALUES ('$order_youhui_id','$user_id','$l_shopId','$time','$order_id','$order_youhui_money')";
	            					$result=$db->query($sql);
								}
								else
								{
									$sql="DELETE FROM `".$oto."_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
									$result=$db->query($sql);
									$l_shopId=$yhq_yz[0]['shop_id'];
									$sql="INSERT INTO ".$oto."_youhui_use_record (`youhui_id`,`userId`,`shopId`,`useTime`,`orderId`,`money`) VALUES ('$order_youhui_id','$user_id','$l_shopId','$time','$order_id','$order_youhui_money')";
	            					$result=$db->query($sql);
								}
							}
						}
						
					}
				}
		}
		else if($body_type=='userId')
		{
			$user_id=$body[1];
	        $money=$_POST['total_fee'];
	        $type='alipay';
	        $orderNo=$_POST['trade_no'];
	        $time=date('Y-m-d H:i:s');
	        $time2=time();
			$sql="select * from `".$oto."_users` where `userId`='".$user_id."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$user_info[]=$row;//将取得的所有数据赋值给person_info数组
			}
			$sql="select * from `".$oto."_money_record` where `orderNo`='".$orderNo."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$record[]=$row;//将取得的所有数据赋值给person_info数组
			}
			if(!isset($record))
			{
				$balance=$user_info[0]['userMoney']+$money;
				if($type=='weixin')
				{
					$cz_type='微信充值';
					$pay_way_lin=2;
				} 
				if($type=='alipay')
				{
					$cz_type='支付宝充值';
					$pay_way_lin=1;
				} 
				$hmoney=$user_info[0]['userMoney']+$money;
				$sql="update ".$oto."_users set userMoney='$hmoney' where userId='{$user_id}'";
				$result2=$db->query($sql);
				$sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`balance`,`time`,`IncDec`,`type`,`remark`,`payWay`) VALUES ('$user_id','$orderNo','$money','$balance','$time2','1','3','$cz_type','$pay_way_lin')";
	            $result=$db->query($sql);
	            // if($result2)
	            // {
	            // 	$data[0]['pan']='true';
	            // 	echo "SUCCESS";
	            // }
	            // else
	            // {
	            // 	$data[0]['pan']='false';
	            // }
			}
		}
	}
	echo "success";
?>